<?php

declare(strict_types=1);

/**
 * system exception handler here record
 * @author modified by kinami chen 
 */
namespace App\Exception\Handler;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Throwable;
use App\Service\Code\Normal;
use App\Model\PssLogModel\InterfaceRequest;

class AppExceptionHandler extends ExceptionHandler
{
    /**
     * @var StdoutLoggerInterface
     */
    protected $logger;
    
    /**
     * $var ServerRequestInterface
     */
    protected $request;

    public function __construct(StdoutLoggerInterface $logger,ServerRequestInterface $request)
    {
        $this->logger = $logger;
        $this->request = $request;
    }

    /**
     * //return $response->withHeader('Server', 'bangmai-server')->withStatus(500)->withBody(new SwooleStream('bangmai oms server error.'));
     * {@inheritDoc}
     * @see \Hyperf\ExceptionHandler\ExceptionHandler::handle($throwable, $response)
     */
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        
        //logger('error','oms-error')->error($throwable->getMessage());
        //$this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
        //$this->logger->error($throwable->getTraceAsString());
        
        //终止异常回话请求，抛出异常处理
        $this->stopPropagation();
        
        //记录接口错误日志，内部异常
        $response_data = [
            'errorMsg'  => $throwable->getMessage(),
            'errorLine' => $throwable->getLine(),
            'errorFile' => $throwable->getFile()
        ];
        $param = [
            'interface_code'    => 'sys_error',
            'bid'               => 0,
            'type'              => 0,
            'request_ip'        => getIp(),
            'request_use_time'  => '0.000',
            'request_param'     => json_encode($this->request->getParsedBody(),JSON_UNESCAPED_UNICODE),
            'response_data'     => json_encode($response_data,JSON_UNESCAPED_UNICODE),
            'response_code'     => 0,
            'response_msg'      => $throwable->getMessage(),
        ];
        InterfaceRequest::instance()->addLog($param);
        return response()->json(Normal::returnCode(500,"系统繁忙，请稍后再试"));
    }
    
    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}